<!--
 * @Description: 日志管理
 * @Author: xuzp4
 -->
<template>
  <div class="parent d-flex flex-column">
    <div class="header d-flex ai-center">
      <MyButton class="add mr-10" icon="el-icon-plus" @click="handleAdd">
        {{ $t("sys_equ_addEqu") }}
      </MyButton>
      <span class="mr-20">{{ $t("device_computing_Power") }}</span>
      <el-progress
        :percentage="percentage"
        color="#1abc9c"
        define-back-color="#8cddcd"
        :stroke-width="24"
        text-color="#fff"
        text-inside
        :format="formatProgress"
      ></el-progress>
    </div>
    <MyTable
      ref="table"
      class="flex-1"
      :data="tableData"
      stripe
      style="width: 100%"
      row-key="channel"
      :expand-row-keys="expandedRows"
    >
      <el-table-column type="expand">
        <template slot-scope="{ row }">
          <el-form
            :model="row"
            inline
            class="form-table-expand"
            label-width="140px"
          >
            <div class="task_content" v-if="row.task_type.includes('body')">
              <p class="title">
                {{ $t("task_type_body") }}
              </p>
              <el-form-item
                :label="item.label"
                v-for="item in body_sub_task_list"
                :key="item.label"
                class="mr-20"
              >
                <el-switch
                  :value="isSwitchChecked(row.body_sub_task, item.value)"
                  @change="
                    (val) =>
                      handleSwitchChange(row, 'body_sub_task', item.value, val)
                  "
                  :disabled="item.roiKey && !row[item.roiKey]"
                >
                </el-switch>
                <MyButton
                  @click="handleSetAlarm(row, item)"
                  class="add ml-20"
                  >{{ $t("config_task") }}</MyButton
                >
              </el-form-item>
            </div>
            <div class="task_content" v-if="row.task_type.includes('cyclist')">
              <p class="title">{{ $t("task_type_cyclist") }}</p>
              <el-form-item
                v-for="item in cyclist_sub_task_list"
                :label="item.label"
                :key="item.label"
                class="mr-20"
              >
                <el-switch
                  :value="isSwitchChecked(row.cyclist_sub_task, item.value)"
                  @change="
                    (val) =>
                      handleSwitchChange(
                        row,
                        'cyclist_sub_task',
                        item.value,
                        val
                      )
                  "
                  :disabled="item.roiKey && !row[item.roiKey]"
                >
                </el-switch>
                <MyButton
                  @click="handleSetAlarm(row, item)"
                  class="add ml-20"
                  >{{ $t("config_task") }}</MyButton
                >
              </el-form-item>
            </div>
            <div class="task_content" v-if="row.task_type.includes('abnormal')">
              <p class="title">{{ $t("status_warn") }}</p>
              <el-form-item
                v-for="item in abnormal_sub_task_list"
                :label="item.label"
                :key="item.label"
                class="mr-20"
              >
                <el-switch
                  :value="isSwitchChecked(row.abnormal_sub_task, item.value)"
                  @change="
                    (val) =>
                      handleSwitchChange(
                        row,
                        'abnormal_sub_task',
                        item.value,
                        val
                      )
                  "
                  :disabled="item.roiKey && !row[item.roiKey]"
                >
                </el-switch>
                <MyButton
                  @click="handleSetAlarm(row, item)"
                  class="add ml-20"
                  >{{ $t("config_task") }}</MyButton
                >
              </el-form-item>
            </div>
            <div
              class="task_content"
              v-if="row.task_type.includes('violation_operate')"
            >
              <p class="title">{{ $t("violation_warn") }}</p>
              <el-form-item
                v-for="item in violate_operate_sub_task_list"
                :label="item.label"
                :key="item.label"
                class="mr-20"
              >
                <el-switch
                  :value="
                    isSwitchChecked(row.violate_operate_sub_task, item.value)
                  "
                  @change="
                    (val) =>
                      handleSwitchChange(
                        row,
                        'violate_operate_sub_task',
                        item.value,
                        val
                      )
                  "
                  :disabled="item.roiKey && !row[item.roiKey]"
                >
                </el-switch>
                <MyButton
                  @click="handleSetAlarm(row, item)"
                  class="add ml-20"
                  >{{ $t("config_task") }}</MyButton
                >
              </el-form-item>
            </div>
            <div
              v-if="
                !['body', 'cyclist', 'abnormal'].some((item) =>
                  row.task_type.includes(item)
                )
              "
            >
              {{ $t("emptyData") }}
            </div>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        width="120"
        type="index"
        :label="$t('common.order_number')"
        sortable
      ></el-table-column>
      <el-table-column
        prop="channel"
        :label="$t('channelNumber')"
        sortable
        min-width="120"
      ></el-table-column>
      <el-table-column
        prop="camera_name"
        :label="$t('channelName')"
        sortable
        min-width="120"
      ></el-table-column>
      <el-table-column :label="$t('sys_equ_ipOrDomain')">
        <template slot-scope="{ row }">
          <span>{{ row.protocol === "rtsp" ? row.url : row.ip }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="camera_mode"
        :label="$t('sys_equ_equType')"
        sortable
        min-width="120"
        :formatter="formatEquType"
      ></el-table-column>
      <el-table-column
        prop="task_type"
        :label="$t('task_type')"
        sortable
        min-width="120"
        :formatter="formatTaskType"
      ></el-table-column>
      <el-table-column
        prop="protocol"
        :label="$t('sys_equ_protocol') + '/' + $t('manufacturer')"
        sortable
        min-width="120"
        :format="formatProtocal"
      ></el-table-column>
      <el-table-column
        prop="port"
        :label="$t('sys_equ_port')"
        sortable
        min-width="120"
      ></el-table-column>
      <el-table-column
        prop="status"
        :label="$t('sys_equ_onlineStat')"
        sortable
        min-width="120"
        :format="formatStatus"
      >
        <template slot-scope="scope">
          <i
            v-if="scope.row.status == 1"
            class="equipment-status status-green"
          ></i>
          <i v-else class="equipment-status status-red"></i>
          <span>{{ formatStatus(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('operation')" min-width="180px">
        <template slot-scope="scope">
          <MyButton
            class="text"
            @click="handleShow(scope.row)"
            type="text"
            size="small"
          >
            {{ $t("common.view") }}
          </MyButton>
          <span class="ml-10 mr-10">|</span>
          <MyButton
            class="text"
            @click="handleEdit(scope.row)"
            type="text"
            size="small"
          >
            {{ $t("common.edit") }}
          </MyButton>
          <span class="ml-10 mr-10">|</span>
          <MyButton
            class="text"
            type="text"
            size="small"
            @click="handleDelete(scope.row)"
            >{{ $t("common.delete") }}</MyButton
          >
        </template>
      </el-table-column>
    </MyTable>
    <Detail
      :visible.sync="isDetailShow"
      :row="row"
      :vehicleLibList="vehicleLibList"
      :lib_list="lib_list"
    />
    <AddDialog
      @refresh="getList"
      :vehicleLibList="vehicleLibList"
      :visible.sync="isAddShow"
      :editType="editType"
      :row="row"
      :restPower="restPower"
    />
    <SetWarnDialog
      :visible.sync="isSetWarnShow"
      @refresh="getList"
      :row="row"
      :setItem="setItem"
    />
  </div>
</template>

<script>
import { getCamera, getAllLib } from "@/services";
import Detail from "./Detail";
import { getvehicleLib, deleteCamera, editCamera } from "./service";
import * as CONSTANT from "./CONSTANT";
import AddDialog from "./AddDialog.vue";
import util from "@/utils";
import SetWarnDialog from "./SetWarnDialog";
export default {
  components: { Detail, AddDialog, SetWarnDialog },
  data() {
    const { equip_type_list, task_type_list, protocol_list, status_list } =
      CONSTANT;
    return {
      expandedRows: [], // Store expanded rows
      setItem: {},
      isDetailShow: false,
      isSetWarnShow: false,
      editType: "add",
      tableData: [],
      equip_type_list,
      task_type_list,
      protocol_list,
      status_list,
      vehicleLibList: [],
      lib_list: [],
      used_computing_power: void 0,
      computing_power_capacity: void 0,
      row: {},
      isAddShow: false,
      body_sub_task_list: [
        {
          label: this.$t("alarm_type_brawl"), // 打架斗殴检测
          value: "1",
          is_warn_time_show: true,
          warn_time: "fight_alarm_gap",
        },
        {
          label: this.$t("alarm_type_utumble"), // 摔倒检测
          value: "2",
          is_warn_time_show: true,
          warn_time: "tumble_alarm_gap",
        },
        {
          label: this.$t("alarm_type_smoke"), // 抽烟检测
          value: "3",
          is_warn_time_show: true,
          warn_time: "smoke_alarm_gap",
        },
        {
          label: this.$t("alarm_type_call"), // 打电话检测
          value: "5",
          is_warn_time_show: true,
          warn_time: "call_alarm_gap",
        },
        {
          label: this.$t("alarm_type_helmet"), // 安全帽检测
          value: "6",
          is_warn_time_show: true,
          warn_time: "helmet_alarm_gap",
        },
        {
          label: this.$t("alarm_type_uniform"), // 工服检测
          value: "7",
          is_work_cloth_color_show: true,
          is_warn_time_show: true,
          warn_time: "work_cloth_alarm_gap",
        },
        {
          label: this.$t("alarm_type_invade"), // 行人闯入
          value: "10",
          is_warn_time_show: true,
          is_invade_time_threshold_show: true,
          is_invade_body_part_show: true,
          roiPolygon: "invade_area",
          roiType: "polygon",
          warn_time: "invade_alarm_gap",
        },
        {
          label: this.$t("alarm_type_Leaving"), // 人员离岗
          value: "11",
          is_warn_time_show: true,
          is_leave_with_oiltanker_show: true,
          is_leave_time_threshold_show: true,
          is_leave_num_threshold_show: true,
          roiPolygon: "leave_area",
          roiType: "polygon",

          warn_time: "leave_alarm_gap",
        },
        {
          label: this.$t("alarm_type_sleeping"), // 人员睡岗
          value: "4",
          is_doze_time_threshold_show: true,
          warn_time: "doze_alarm_gap",
        },
        {
          label: this.$t("alarm_type_crowd"), // 人群密度
          value: "14",
          warn_time: "crowd_alarm_gap",
          is_crowd_threshold_show: true,
          roiPolygon: "crowd_area",
          roiType: "polygon",
        },
        {
          label: this.$t("alarm_type_armed"), // 围栏布防
          value: "9",
          is_over_boundary_body_part_show: true,
          is_over_boundary_direction_show: true,
          roiLine: "over_boundary_line", // over_boundary_line "1316*636,984*464"
          roiType: "line",
        },
        {
          label: this.$t("alarm_type_lean_out"), // 身体探出
          value: "12",
          warn_time: "lean_out_alarm_gap",
          is_lean_out_line_body_part_show: true,
          is_lean_out_area_body_part_show: true,
          roiPolygon: "lean_out_foothold_area",
          roiLine: "lean_out_boundary_line",
          roiType: "line,polygon",
        },
        {
          label: this.$t("alarm_type_mask"), // 口罩检测
          value: "17",
          warn_time: "mask_alarm_gap",
        },
        {
          label: this.$t("alarm_type_helmet_s"), // 工帽检测
          value: "18",
          is_work_cap_color_show: true,
          warn_time: "work_cap_alarm_gap",
        },
        {
          label: this.$t("alarm_type_clothes_f"), // 反光衣
          value: "8",
          warn_time: "reflective_cloth_alarm_gap",
        },
      ],
      cyclist_sub_task_list: [
        {
          label: this.$t("alarm_type_cyclist"), //非机动车闯入
          value: "2",
          roiPolygon: "n_vel_invade_area",
          warn_time: "n_vel_invade_alarm_gap",
          roiType: "polygon",
        },
      ],
      abnormal_sub_task_list: [
        {
          label: this.$t("alarm_type_fire"), // 明火检测
          value: "1",
          warn_time: "firesmoke_alarm_gap",
        },
        {
          label: this.$t("alarm_type_thickSmoke"), //浓烟检测
          value: "4",
          warn_time: "thicksmoke_alarm_gap",
        },
        {
          label: this.$t("alarm_type_fire_fighting_occupy"), //消防通道占用
          value: "2",
          warn_time: "fire_exit_alarm_gap",
          is_fire_exit_time_threshold_show: true,
          roiPolygon: "fire_exit_area",
          roiType: "polygon",
        },
        {
          label: this.$t("alarm_type_fire_p"), // 烟火离人
          value: "3",
          is_firesmoke_unattend_time_threshold_show: true,
          warn_time: "firesmoke_unattend_alarm_gap",
          roiPolygon: "firesmoke_unattend_area",
          roiType: "polygon",
        },
        {
          label: this.$t("alarm_type_mouse"), //鼠患检测
          is_ratdsize_min_show: true,
          is_ratdsize_max_show: true,
          is_ratd_schedule_show: true,
          warn_time: "ratd_alarm_gap",
          value: "5",
          roiPolygon: "ratd_area",
          roiType: "polygon",
        },
      ],
      violate_operate_sub_task_list: [
        {
          label: this.$t("alarm_type_fire_extinguisher"), //灭火器检测
          value: "1",
          warn_time: "fireExtinguisher_alarm_gap",
          is_fireExtinguisher_with_oiltanker_show: true,
          is_fireExtinguisher_time_threshold_show: true,
          roiPolygon: "fireExtinguisher_area",
          roiType: "polygon",
        },
        {
          label: this.$t("alarm_type_electrostatic_clamp_detection"), //静电释放检测
          value: "2",
          is_static_line_time_threshold_show: true,
        },
      ],
    };
  },
  computed: {
    percentage() {
      if (!this.used_computing_power) return 0;
      return (this.used_computing_power / this.computing_power_capacity) * 100;
    },
    restPower() {
      return this.computing_power_capacity - this.used_computing_power;
    },
  },
  mounted() {
    this.getList();
    this.getvehicleLib();
    this.getAllLib();
    this.timer = setInterval(() => {
      this.getList(false);
    }, 5000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    handleSetAlarm(row, item) {
      this.isSetWarnShow = true;
      this.row = { ...row };
      this.setItem = item;
    },
    isSwitchChecked(fieldValue, value) {
      return fieldValue.split(",").includes(value);
    },
    handleSwitchChange(row, fieldValue, value, checked) {
      let values = row[fieldValue] ? row[fieldValue].split(",") : [];
      if (checked) {
        values.push(value);
      } else {
        values = values.filter((v) => v !== value);
      }
      row[fieldValue] = values.join(",");
      this.uploadSwitchState(row);
    },
    async uploadSwitchState(row) {
      const params = {
        ...row,
      };
      try {
        const res = await editCamera(params);
        if (res.code == 0) {
          util.msg.success("edit_success");
        }
      } finally {
        this.getList(false);
      }
    },
    // async updatePower() {
    //   const res = await getCamera({isLoading});
    //   if (res.code == 0) {
    //     this.used_computing_power = res.data.used_computing_power;
    //     this.computing_power_capacity = res.data.computing_power_capacity;
    //   }
    // },
    async getList(isLoading = true) {
      const res = await getCamera({ isLoading });
      if (res.code == 0) {
        this.tableData = res.data.camera;
        this.used_computing_power = res.data.used_computing_power;
        this.computing_power_capacity = res.data.computing_power_capacity;
        this.$nextTick(() => {
          this.restoreExpandedRows();
        });
      }
    },
    restoreExpandedRows() {
      // Restore expanded rows after data update
      this.expandedRows.forEach((row) => {
        // Find corresponding row in updated data
        const updatedRow = this.tableData.find(
          (dataRow) => dataRow.channel === row.channel
        );
        if (updatedRow) {
          // Expand row in updated data
          this.$refs.table.toggleRowExpansion(updatedRow, true);
        }
      });
    },
    handleAdd() {
      if (this.percentage === 100) {
        return this.$message.warning(this.$t("sys_equ_deleteErr"));
      }
      this.row = {};
      this.editType = "add";
      this.isAddShow = true;
    },
    handleShow(row) {
      this.row = { ...row };
      this.isDetailShow = true;
    },
    handleEdit(row) {
      this.row = { ...row };
      this.editType = "edit";
      this.isAddShow = true;
    },
    handleDelete(row) {
      util.confirm(
        this.$t("sys_equ_title_dele"),
        this.$t("sys_equ_delete"),
        this.$t("confDelete"),
        this.$t("cancel"),
        async () => {
          const params = {
            channel: row.channel,
          };
          await deleteCamera(params);
          this.$message.success(this.$t("deleteOk"));
          this.getList();
        }
      );
    },
    formatEquType(row, column, cellValue) {
      return this.equip_type_list.find((item) => item.value == cellValue).label;
    },
    formatTaskType(row, column, cellValue) {
      return cellValue
        .split(",")
        .map((item) => {
          const info = this.task_type_list.find((item2) => item2.value == item)
          return info && info.label;
        })
        .join(",");
    },
    formatProtocal(row, column, cellValue) {
      return this.protocol_list.find((item) => item.value == cellValue).label;
    },
    formatStatus(cellValue) {
      return this.status_list.find((item) => item.value == cellValue).label;
    },
    async getvehicleLib() {
      const res = await getvehicleLib();
      if (res.code == 0) {
        this.vehicleLibList = res.data;
      }
    },
    async getAllLib() {
      const res = await getAllLib();
      if (res.code == 0) {
        this.lib_list = res.data;
      }
    },
    formatProgress() {
      return this.used_computing_power
        ? `${this.used_computing_power}/${this.computing_power_capacity}`
        : "";
    },
  },
};
</script>

<style lang="less" scoped>
.parent {
  font-size: 14px;
  height: 100%;
  background: #ffffff;
  border-radius: 20px;
  padding: 20px;
  .form-table-expand {
    padding: 20px;
    .task_content {
      /deep/ .el-form-item {
        width: 22%;
      }
      .el-form-item:nth-of-type(4n + 0),
      .el-form-item:last-child {
        border: none;
      }
    }
    .title {
      padding: 5px 14px;
      font-size: 16px;
      border-bottom: 1px solid #253250;
      color: #90a1c8;
      width: 100px;
      display: block;
    }
    /deep/ .el-form-item {
      position: relative;
      border-right: 1px dashed #253250;
      margin-right: 20px;
    }
  }
  /deep/ .el-progress {
    width: 500px;
  }
  .equipment-status {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: inline-block;
    vertical-align: middle;
    margin-right: 10px;
  }
  .status-green {
    background: #4dd964;
  }
  .status-red {
    background: #ef5350;
  }
}
</style>
